/**
 * 定义ui公共模块
 */
(function(window, angular, undefined){

	var component = angular.module('water.common.formCheck',[]);
	
	
	/**
	 * 基础弹框组件
	 */
	component.directive("fromCheckSubmit", function($formCheckService) {
		return {
		    restrict: "A",     
		    scope: {              // 设置指令对于的scope 
		      comSubmit:"&"
		    },
		    link:function($scope, elm, attrs, controller){
		    	$(elm).bind("click",function(event){
		    		var form = $(elm).parents("form")
					var result = $formCheckService.checkAllInput(form);
					if(result){
						$scope.comSubmit();
					}
				});
	        }
		 } 
	});
	
	/**
	 * 基础弹框组件
	 */
	component.directive("fromCheckRule", function($formCheckService) {
		return {
		    restrict: "A",     
		    scope: {              // 设置指令对于的scope 
		    	fromCheckRule:'@'
		    },
		    link:function($scope, elm, attrs, controller){
		    	$formCheckService.bindCheck(elm);
	        }
		 } 
	});
	
	component.service('$formCheckService',function($waterDataCommon){
		
		/**
		 * 定义校验规则
		 */
		var ruleCheck = {
			"require":{
				desc:'必填项',
				check:function(val){
					if(val == undefined || val == ""){
						return false;
					}
					else{
						return true;
					}
				}
			},
			"AbcAndNumber":{
				desc:'只允许数字和字母',
				regex: /^[A-Za-z0-9]+$/
			},
			"Abc":{
				desc:'只允许字母',
				regex: /^[A-Za-z]+$/
			},
			"number":{
				desc:'只能填数字',
				regex: /^[0-9]+$/
			},
			"float":{
				desc:'只能填数字',
				regex:/^[0-9]+(.{1}[0-9]+){0,1}$/
			},
			"chinese":{
				desc:"只能填写中文",
				regex:/^[\u4e00-\u9fa5]{0,}$/
			},
			"phone":{
				desc:"只能填11位手机号码",
				regex:/0?(13|14|15|18)[0-9]{9}/
			},
			"telphone":{
				desc:"只能填写12位固定电话号码",
				regex:/[0-9-()（）]{7,18}/
			},
			"email":{
				desc:"只能填写xx@xx.xx格式",
				regex: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/
			},
			"IdCard":{
				desc:"只能填写正确身份证",
				regex:/\d{17}[\d|x]|\d{15}/
			},
			"AbcNumberUnderline":{
				desc:"只能填字母、下划线、数字",
				regex:/\w$/
			},
			"url":{
				desc:"只能填正确网站",
				regex:/^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/
			},
			"ip":{
				desc:"格式如:xxx.xxx.xxx.xxx",
				regex:/(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)/
			},
			"ZipCode":{
				desc:"只能填写6位数字邮编",
				regex: /\d{6}/
			},
			"ChinesAndAbc":{
				desc:"只能输入中文和字母",
				regex:/[a-zA-Z\u4e00-\u9fa5]+$/
				
			},
			"phoneOrTelephone":{
				desc:"只能输入座机号码或者手机号码",
				regex:/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/
			}
			
		}
		
		/**
		 * 移除提示信息
		 */
		function removeMsg(elm){
			$(elm).nextAll(".form-check-msg").remove();
		}
		
		/**
		 * 校验这个输入要素
		 */
		function handleCheck (elm){
			var value = getInputValue(elm);
			var rules = getRules(elm);
			for(var i =0;i<rules.length;i++){
				var rule = rules[i].rule;
				var msg = rules[i].msg;
				
				/**
				 * 如果值为空，而且当前的规则不是必填检查，则跳过
				 */
				if(!value && rule != "require"){
					continue;
				}
				
				var ruleCheckFun = ruleCheck[rule];
				
				/**
				 * 如果规则不存在则返回,或者规则没有定于检查函数则返回
				 */
				if(!ruleCheckFun || (!ruleCheckFun.check && !ruleCheckFun.regex)){
					continue;
				}
				
				if(!msg){
					msg = ruleCheckFun.desc;
				}
				
				var result;
				
				if(ruleCheckFun.regex){
					result = ruleCheckFun.regex.test(value);
				}
				else{
					result = ruleCheckFun.check(value);
				}
				
				if(!result){
					onValError(elm, msg);
					return false;
				}
			}
			return true;
		}
		
		/**
		 * 校验错误后执行的操作,先清除提示信息
		 */
		function onValError(elm,msg){
			removeMsg(elm);
			showMsg(elm, msg);
		}
		
		/**
		 * 展示提示信息
		 */
		function showMsg(elm,msg){
			$(elm).after("<span class='form-check-msg'>"+msg+"</span>");
		}
		
		/**
		 * 获取要素的值
		 */
		function getInputValue(elm){
			var value = $(elm).val();
			return value;
		}
		
		/**
		 * 获取元素上配置的规则
		 */
		function getRules(elm){
			var rules = [];
			var ruleStr =  $(elm).attr("from-check-rule");
			var rulesObj;
			try {
				rulesObj = eval(ruleStr);
			} catch (e) {
				console.log("from-check-rule："+ruleStr+",设置有误\n" +
						"示例：[{rule:'require',msg:'必填项'},{rule:'AbcAnd123'}]",e);
				return;
			}
			for(var i =0;i<rulesObj.length;i++){
				var ruleItem = rulesObj[i];
				var rule = ruleItem.rule;
				
				if(!rule){
					console.log("from-check-rule："+ruleStr+",设置有误,rule不能为空\n" +
							"示例：[{rule:'require',msg:'必填项'},{rule:'AbcAnd123'}]");
				}
				
				var msg = ruleItem.msg;
				rules.push({
					rule:rule,
					msg:msg
				});
			}
			return rules;
		}
		
		/**
		 * 校验全部的输入框，如果有错误返回false
		 * 否则返回true
		 */
		this.checkAllInput = function(elm){
			var inputs = $("input[from-check-rule]",$(elm));
			for(var i =0;i<inputs.length;i++){
				var result = handleCheck(inputs[i]);
				if(!result){
					return false;
				}
			}
			return true;
		}
		
		/**
		 * 给需要校验的文本框加上校验事件
		 */
		this.bindCheck1 = function(elm){
			var inputs = $("input[from-check-rule]",$(elm));
			var submitBtn = $("input[from-check-submit]",$(elm));
			
			inputs.unbind("blur").bind("blur",function(){
				handleCheck(this);
			});
			inputs.unbind("focus").bind("focus",function(){
				removeMsg(this);
			});
			
			var bindcheck = submitBtn.attr("bindcheck");
			
			if(bindcheck != '1'){
				submitBtn.bind("click",function(event){
					submitBtn.attr("bindcheck","1");
					var result = checkAllInput(elm);
					if(!result){
						//如果检查有问题，阻止事件冒泡 
						event.stopPropagation();
						event.error = 'true';
						submitBtn.attr("hasError",'1');
						return false;
					}
					submitBtn.removeAttr("hasError");
					
					return true;
				});
			}
		}
		
		/**
		 * 给需要校验的文本框加上校验事件
		 */
		this.bindCheck = function(elm){
			
			$(elm).unbind("blur").bind("blur",function(){
				handleCheck(this);
			});
			$(elm).unbind("focus").bind("focus",function(){
				removeMsg(this);
			});
			
		}
		
	})
	
}(window, angular));